<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Medium\Action\Workbench;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\Medium\Contract\MediumContract;
use MoChat\App\Medium\Contract\MediumGroupContract;
use MoChat\App\User\Logic\Traits\UserTrait;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 查询 - 详情.
 * @Controller
 */
class Show extends AbstractAction
{
    use UserTrait;

    /**
     * @Inject
     * @var MediumGroupContract
     */
    protected $mediumGroupService;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/medium/show", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $params['corpId'] = $user['corpId'];
        $params['employeeId'] = $user['id'];
        $id = (int) $this->request->query('id', false);
        if (! $id) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '唯一标识ID必须');
        }

        // 模型查询
        $client = $this->container->get(MediumContract::class);
        $data = $client->getMediumById($id, ['id', 'media_id', 'type', 'content', 'corp_id', 'medium_group_id', 'user_id', 'user_name']);
        if (empty($data)) {
            return [];
        }
        $group = $this->mediumGroupService->getMediumGroupById($data['mediumGroupId'], ['id', 'name']);
        $data['groupName'] = $group['name'] ?? '';
        $data['content'] = $client->addFullPath(Json::decode($data['content']), $data['type']);
        return $data;
    }
}
